package com.cskaoyan._03lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description:
 * @author: 景天
 * @date: 2023/2/22 14:30
 **/
/*
使用Lock解决数据安全问题
 */
public class Demo {
    public static void main(String[] args) {
        SellWindow sellWindow = new SellWindow();
        new Thread(sellWindow,"A窗口").start();
        new Thread(sellWindow,"B窗口").start();
        new Thread(sellWindow,"C窗口").start();
    }
}

class SellWindow implements Runnable{
    // 定义票
    int tickets = 100;
    // 定义一把锁
    Lock lock = new ReentrantLock();
    // run
    @Override
    public void run() {

        while (true) {
            // 获取锁
            // lock()
            lock.lock();
            try {
                // 卖之前进行判断
                if (tickets > 0) {

                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + "卖了第"
                            + (tickets--) + "张票");
                }
            }finally {
                // 释放锁
                // unlock()
                lock.unlock();
            }

        }
    }
}